<template>
    <TopBar></TopBar>
    <div class="body">
        <div class="left">
            <div class="nav">
                <div class="logo">
                    <el-image src="https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/Retail/retail_logo.png"
                        fit="cover"></el-image>
                </div>
                <button @click="router.push('/retail')"><el-icon size="25" class="nav-icon">
                    <Histogram />
                    </el-icon>热门发现</button>
                <button @click="router.push('/retailSub')"><el-icon size="25" class="nav-icon">
                        <Promotion />
                    </el-icon>发布宝贝</button>
                <button @click="router.push('/retailNews')"><el-icon size="25" class="nav-icon">
                        <Comment />
                    </el-icon>我的通知</button>
                <button @click="jumpMyPage"><el-image class="my_avatar" :src="user.avatar"></el-image>我的页面</button>
            </div>
        </div>
        <div class="right">
            <div class="profile-container">
                <div class="profile-header">
                    <div class="avatar-section">
                        <img :src="user.avatar" :alt="user.avatar" class="avatar">
                    </div>
                    <div class="profile-info">
                        <h1 class="username">{{ user.name }}</h1>
                        <p class="user-id">uid: {{ user.uid }}</p>
                        <p class="description">xxxx</p>
                        <div class="stats">
                            <div class="stat-item">
                                <span class="stat-number">{{followToNum}}</span>
                                <span class="stat-label">关注</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-number">{{toFollowNum}}</span>
                                <span class="stat-label">粉丝</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-number">{{Likes}}</span>
                                <span class="stat-label">获赞与收藏</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="tabs">
                    <button v-for="tab in tabs" :key="tab.id" :class="['tab-button', { active: currentTab === tab.id }]"
                        @click="currentTab = tab.id">
                        {{ tab.name }}
                    </button>
                </div>

                <div class="content">
                    <!-- <div v-if="!hasContent" class="empty-state">
                        <img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-j0bGCvcbjr1lhdPXSo8nc9g7vWTBdw.png"
                            alt="Empty state illustration" class="empty-icon">
                        <p class="empty-text">你还没有发布任何内容</p>
                    </div> -->
                    <Waterfall v-if="!card_loading" :list="list" :breakpoints="breakpoints">
                        <template #default="{ item }">
                            <div class="card">
                                <el-image @click="JumpDesc(item.retailUid)" class="card_img" :src="item.retailImage"
                                    fit="cover"></el-image>
                                <div class="info">
                                    <h3>{{ item.retailTitle }}</h3>
                                    <div class="info_desc">
                                        <el-image style="width: 2.5vh;border-radius: 100%;" :src="item.retailAuthorAvatar"
                                            fit="cover"></el-image>
                                        <p>{{ item.retailAuthorName }}</p>
                                        &nbsp;&nbsp;&nbsp;&nbsp;
                                        <p><el-icon style="top: 0.2vh;">
                                                <Star />
                                            </el-icon>{{ item.retailLikes }}</p>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </Waterfall>
                </div>
                <div class="desc">
                    <el-dialog v-model="showDialog" :show-close="false" :modal-close-on-click-modal="true"
                        custom-class="square-dialog">
                        <template #header>
                            <!-- 自定义关闭按钮 -->
                            <button class="custom-close" @click="showDialog = false">×</button>
                        </template>

                        <div class="dialog-content">
                            <div class="desc_left">

                                <el-image :preview-src-list="[desc_info.retailImage]" class="desc_img"
                                    :src="desc_info.retailImage" fit="contain"></el-image>
                                <div class="item_card" v-if="showPostItem">
                                    <el-image style="width:40%;height:100%;border-radius: 15px;"
                                        :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品列表/List/${desc_info.itemImg}.jpg`"></el-image>
                                    <div style="display: flex;flex-direction: column;">
                                        <p style="font-size: 2vh;padding: 1vh;">{{ desc_info.itemName }}</p>
                                        <div style="display: flex;justify-content: space-between;padding-left: 1vh;">
                                            <p style="color: rgba(249, 128, 42, 0.938);font-size: 3vh;font-weight: bold;">
                                                ￥{{ desc_info.itemPrice }}</p>
                                            <el-button type="success" circle><el-icon>
                                                    <SoldOut />
                                                </el-icon></el-button>
                                        </div>

                                    </div>
                                </div>
                            </div>
                            <div class="desc_right">
                                <div class="author_info">
                                    <div class="author_info-one">
                                        <el-avatar class="author_avatar" :src="desc_info.retailAuthorAvatar"
                                            fit="cover"></el-avatar>
                                        <p>{{ desc_info.retailAuthorName }}</p>
                                        <el-button style="margin-left: 30vh;font-weight: bold;" type="success"
                                            round>&nbsp;&nbsp;关注&nbsp;&nbsp;</el-button>

                                    </div>
                                    <div class="author_info-two">
                                        <P style="font-weight: bold; font-size: 2.5vh;color: black;">{{
                                            desc_info.retailTitle }}</P>
                                        <P>{{ desc_info.retailContent }}</P>
                                        <p>{{ desc_info.retailTime }}</p>
                                        <h2 class="text-2xl font-bold mb-4">评论区</h2>
                                    </div>
                                </div>
                                <div class="comment_info">
                                    <div class="comment-section">
                                        <ul v-if="comments.length > 0" class="space-y-6">
                                            <div v-for="comment in comments" :key="comment.commentUid"
                                                class="bg-white rounded-lg shadow-md p-4">
                                                <div class="flex items-start space-x-4">
                                                    <div class="flex-1">
                                                        <div style="display: flex;margin-top: 1vh;gap: 1vh;align-items:center;"
                                                            class="flex items-center justify-between">
                                                            <el-avatar size="small" class="comment-avatar"
                                                                :src="comment.commentUserAvatar"></el-avatar>
                                                            <h3 style="font-weight: normal;" class="font-semibold">{{
                                                                comment.commentUser }}</h3>
                                                        </div>
                                                        <p style="padding-bottom: 1vh;" class="mt-2 text-gray-700">{{
                                                            comment.content }}</p>
                                                        <div style="display: flex;flex-direction: column;">
                                                            <el-image :preview-src-list="[comment.commentImage]"
                                                                v-if="comment.commentImage" :src="comment.commentImage"
                                                                alt="Comment Image" class="comment-image"></el-image>
                                                            <span style="padding-top: 1vh;color: rgb(158, 158, 158);"
                                                                class="text-sm text-gray-500">{{
                                                                    formatDate(comment.commentTime)
                                                                }}</span>
                                                        </div>

                                                        <!-- Nested replies -->
                                                        <ul v-if="comment.replyTos && comment.replyTos.length > 0"
                                                            class="mt-4 space-y-4">
                                                            <div v-for="reply in comment.replyTos" :key="reply.commentUid"
                                                                class="bg-gray-50 rounded-lg p-3">
                                                                <div style="margin-left: 4vh;"
                                                                    class="flex items-start space-x-3">
                                                                    <div class="flex-1">
                                                                        <div style="display: flex;gap: 1vh;align-items:center;"
                                                                            class="flex items-center justify-between">
                                                                            <el-avatar size="small" class="comment-avatar"
                                                                                :src="reply.commentUserAvatar"></el-avatar>
                                                                            <h4 style="font-weight: normal;"
                                                                                class="font-semibold text-sm">{{
                                                                                    reply.commentUser
                                                                                }}</h4>
                                                                        </div>
                                                                        <p style="padding-bottom: 1vh;"
                                                                            class="mt-1 text-sm text-gray-600">{{
                                                                                reply.content }}
                                                                        </p>
                                                                        <div style="display: flex;flex-direction: column;">
                                                                            <el-image
                                                                                :preview-src-list="[reply.commentImage]"
                                                                                v-if="reply.commentImage"
                                                                                :src="reply.commentImage" alt="Reply Image"
                                                                                class="comment-image"></el-image>
                                                                            <span
                                                                                style="padding-top: 1vh;padding-bottom: 4vh;color: rgb(158, 158, 158);"
                                                                                class="text-xs text-gray-500">{{
                                                                                    formatDate(reply.commentTime) }}</span>
                                                                        </div>

                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </ul>
                                        <div style="justify-content: center;align-items: center;" v-else>暂无评论</div>
                                    </div>
                                </div>
                                <div class="comment-input">
                                    <div class="input-container">
                                        <el-input style="padding-left: 2vh;" v-model="newComment" type="textarea" :rows="1"
                                            placeholder="写下你的评论..." class="comment-textarea"></el-input>
                                        <div class="input-actions">
                                            <el-upload action="/api/upload" :show-file-list="false"
                                                :on-success="handleImageSuccess">
                                                <el-button style="margin-left: 2vh;" type="text"><el-icon>
                                                        <Picture></Picture>
                                                    </el-icon> 添加图片</el-button>
                                            </el-upload>
                                            <div>
                                                <el-button @click="deleteLike()" v-if="isPostLike" type="warning"
                                                    circle><el-icon>
                                                        <Pointer />
                                                    </el-icon></el-button>
                                                <el-button @click="addLike()" v-else type="danger" circle><el-icon>
                                                        <Pointer />
                                                    </el-icon></el-button>
                                                <el-button style="font-weight: bold;" type="success" @click="submitComment"
                                                    round>发送</el-button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-dialog>
                </div>
            </div>
        </div>
    </div>
    <Footer></Footer>
</template>


<script setup>
import TopBar from '@/component/TopBar.vue'
import Footer from '@/component/Footer.vue'
import { ref, onMounted } from 'vue'
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next";
import { useRoute } from "vue-router";
import router from '../../router/index.js'
// 在顶部导入图标
import { Picture } from '@element-plus/icons-vue'
import "vue-waterfall-plugin-next/dist/style.css";
import request from '../../utils/request';
import { ElNotification } from 'element-plus'

//优化卡片显示问题
const card_loading = ref(true);

// 响应式数据
const list = ref({})
const user = ref({});
const desc_info = ref({})
const comments = ref({})
const followToNum=ref();
const toFollowNum=ref();

//详情窗口bool值
const showDialog = ref(false)

//帖子商品
const showPostItem = ref(false)

// 新增的响应式数据
const newComment = ref('');
const commentImage = ref(null);

//判断点赞
const isPostLike = ref(false);

// 新增的方法
const handleImageSuccess = (response) => {
    commentImage.value = response.url;
};

//点赞
const addLike = async () => {
    await request.get("/api/retail/addLike", {
        params: {
            uid: user.value.uid,
            type: "post",
            content: desc_info.value.retailUid
        }
    }).then(async res => {
        ElNotification({
            title: '点赞成功',
            message: '用户点赞帖子',
            type: 'success',
        })
        isPostLike.value = true;
        const news = ref({});
        news.value.image = user.value.avatar;
        news.value.uid = user.value.uid;
        news.value.toUid = desc_info.value.uid;
        news.value.content = "点赞了你的帖子";
        news.value.type = "消息通知";
        news.value.status = 0;
        news.value.createdAt = new Date();
        news.value.updatedAt = new Date();
        await request.post("/api/retail/addNotification", news.value).then(res => {
            console.log(res.data);
        })
    })
}

//取消点赞
const deleteLike = async () => {
    await request.get("/api/retail/deleteLike", {
        params: {
            uid: user.value.uid,
            type: "post",
            content: desc_info.value.retailUid
        }
    }).then(res => {
        ElNotification({
            title: '取消点赞成功',
            message: '用户取消点赞帖子',
            type: 'success',
        })
        isPostLike.value = false;
    })
}

const submitComment = async () => {
    if (!newComment.value.trim()) return;

    const commentData = {
        content: newComment.value,
        commentImage: commentImage.value,
        postItem: desc_info.value.retailUid,
        commentUser: user.value.uid,
        commentTime: formatDate(new Date()),
        replyToUid: null
    };

    try {
        await request.post('/api/retail/addComment', commentData);
        // 提交后刷新评论
        const res = await request.get("/api/retail/selectPostCommentByUid", {
            params: { postItem: desc_info.value.retailUid }
        }).then(async res => {
            comments.value = res.data;

            const news = ref({});
            news.value.image = user.value.avatar;
            news.value.uid = user.value.uid;
            news.value.toUid = desc_info.value.uid;
            news.value.content = "评论了你的帖子";
            news.value.type = "消息通知";
            news.value.status = 0;
            news.value.createdAt = new Date();
            news.value.updatedAt = new Date();
            await request.post("/api/retail/addNotification", news.value).then(res => {
                console.log(res.data);
            }).catch(error => {
                console.error("请求失败", error);
            })
        });
        // 清空输入
        newComment.value = '';
        commentImage.value = null;
    } catch (error) {
        console.error('评论提交失败:', error);
    }
};

const jumpMyPage = () => {
    if (!sessionStorage.getItem('uid')) {
        ElNotification({
            title: '失败',
            message: '请先登录',
            type: 'error',
        })
        setTimeout(() => {
            router.push('/login');
        }, 1000);
    }
    else {
        router.push('/retailMy')
    }
}

const getUserInfo = () => {
    const uid = sessionStorage.getItem('uid');
    if (uid) {
        const uidObj = JSON.parse(uid);
        request.get('/api/user/GetUserInfo', {
            params: {
                uid: uidObj
            }
        }).then(res => {
            user.value = res.data;
        }).catch(error => {
            console.error("请求失败", error);
        })
    } else {
        console.log("未登录");
        user.value.avatar = "https://bu.dusays.com/2024/12/28/677018da4485e.png";
    }
}

const JumpDesc = async (uid) => {
    console.log("跳转详情页")
    console.log(uid)
    await request.get("/api/retail/selectPostDescByUid", {
        params: {
            retailUid: uid
        }
    }).then(res => {
        console.log(res.data);
        desc_info.value = res.data
    })

    await request.get("/api/retail/selectPostItemByUid", {
        params: {
            retailUid: uid
        }
    }).then(res => {
        if (res.data != null) {
            desc_info.value.itemImg = res.data.itemImg;
            desc_info.value.itemName = res.data.itemName;
            desc_info.value.itemPrice = res.data.itemPrice;
            showPostItem.value = true;
        }
        else {
            showPostItem.value = false;
        }
    })

    await request.get("/api/retail/selectPostCommentByUid", {
        params: {
            postItem: uid
        }
    }).then(res => {
        comments.value = res.data
        console.log("我是评论");
        console.log(comments.value);
    })

    await request.get("/api/retail/isPostLike", {
        params: {
            uid: user.value.uid,
            retailUid: uid
        }
    }).then(res => {
        console.log("我是点赞", res.data);
        isPostLike.value = res.data;
    })

    showDialog.value = true;
}

const Likes=ref();

const GetUserLike=(uid)=>{
    request.get("/api/retail/selectUserLike", {
        params:{
            uid: uid
        }
    }).then(res => {
        Likes.value = res.data;
    }
    )
}

const GetUserFollows=()=>{
    const followRetail=ref({});
    followRetail.value.followTo=user.value.uid;
    request.post("/api/retail/follow",followRetail.value,{
        params:{
            type:"follows"
        }
    }).then(res=>{
        console.log("我是粉丝",res.data);
        followToNum.value=res.data.followToNum;
        toFollowNum.value=res.data.toFollowNum;
    })
}

// 初始化加载
onMounted(async () => {
    await getUserInfo();
    const uid =JSON.parse(sessionStorage.getItem('uid'));
    await request.get('/api/retail/selectPostByUid',{
        params: { uid: uid }
    }).then(res => {
        list.value = res.data
        console.log(res.data);
    }).catch(err => {
        console.error('请求失败:', err)
    }).finally(() => {
        card_loading.value = false;
    })

    await GetUserLike(uid);
    await GetUserFollows();
})

// 格式化日期的函数
const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
};

</script>

<style scoped>
.body {
    width: 100%;
    height: 100%;
    display: flex;
}

.left {
    width: 15%;
    height: 100%;
}

.nav {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 4vh;
    gap: 3vh;
    justify-content: center;
}

.nav button {
    font-size: large;
    font-weight: bold;
    transition: all 0.3s ease;
}

.nav button:hover {
    transform: scale(1.05);
}

.nav-icon {
    top: 0.7vh;
}


.logo {
    width: 50%;
}

.my_avatar {
    width: 3vh;
    top: 0.7vh;
    border-radius: 50%;
}

.right {
    width: 85%;
    height: 100%;
    background-color: #f4f4f4;
    padding: 20px;
    box-sizing: border-box;
}

.profile-container {
    max-width: 100%;
    margin: 0 auto;
    padding: 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.profile-header {
    display: flex;
    align-items: flex-start;
    gap: 24px;
    margin-bottom: 32px;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
}

.profile-info {
    flex: 1;
}

.username {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 8px 0;
}

.user-id {
    color: #999;
    font-size: 14px;
    margin: 0 0 8px 0;
}

.description {
    font-size: 14px;
    margin: 0 0 16px 0;
}

.stats {
    display: flex;
    gap: 24px;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stat-number {
    font-weight: 600;
    font-size: 16px;
}

.stat-label {
    color: #666;
    font-size: 14px;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #eee;
    margin-bottom: 24px;
}

.tab-button {
    padding: 12px 24px;
    background: none;
    border: none;
    font-size: 16px;
    color: #666;
    cursor: pointer;
    position: relative;
}

.tab-button.active {
    color: #000;
}

.tab-button.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #000;
}

.content {
    min-height: 400px;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 0;
}

.empty-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-text {
    color: #999;
    font-size: 14px;
}

.card {
    transition: all 0.3s ease;
}

.card:hover {
    transform: scale(1.01);
}

.goods-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
}

.goods-card img {
    width: 100%;
    display: block;
}

.info {
    padding: 12px;
}

.info_desc {
    display: flex;
    gap: 1vh;
}

.info h3 {
    margin: 0 0 8px;
    font-size: 16px;
}

.info p {
    margin: 0;
    color: #383838;
    font-size: 14px;
}

/* 详情窗口 */
/* 自定义关闭按钮 */
.custom-close {
    position: absolute;
    top: 5px;
    right: 15px;
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
    z-index: 2000;
}

/* 内容居中 */
.dialog-content {
    display: flex;
}

/* 深度选择器修改 el-dialog 样式 */
:deep(.square-dialog) {
    border-radius: 8px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33) !important;

    /* 确保弹窗是正方形 */
    .el-dialog__body {
        padding: 0px;
        height: auto !important;
        width: auto !important;
    }
}

/* 动画效果 */
:deep(.el-dialog) {
    transition: all 0.3s ease;
}

:deep(.el-dialog__wrapper) {
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 进入动画 */
:deep(.el-dialog-enter-active .el-dialog) {
    transform: scale(0.7);
    opacity: 0;
}

:deep(.el-dialog-enter-to .el-dialog) {
    transform: scale(1);
    opacity: 1;
}

/* 离开动画 */
:deep(.el-dialog-leave-active .el-dialog) {
    transform: scale(1);
    opacity: 1;
}

:deep(.el-dialog-leave-to .el-dialog) {
    transform: scale(0.7);
    opacity: 0;
}

.desc_left {
    width: 40%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    /* height: 650px; */
}

.item_card {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background-color: rgb(200, 253, 237);
    border-radius: 15px;
    width: 90%;
    height: 18%;
}

.desc_img {
    width: 100%;
    object-fit: contain;
    max-width: 100%;
    max-height: 100%;
    margin: auto;
}

.desc_right {
    display: flex;
    flex-direction: column;
    width: 60%;
    height: 650px;
}

.author_info {
    width: 100%;
    height: 35%;
}

.author_info-one {
    padding: 1vh;
    display: flex;
    align-items: center;
    gap: 2vh;
}

.author_info-two {
    padding: 1vh;
    display: flex;
    flex-direction: column;
    gap: 1vh;
}


.comment_info {
    width: 100%;
    height: 55%;
}

.comment-section {
    max-width: 800px;
    margin: 0 auto;
    padding: 1rem;
    height: 100%;
    overflow: auto;
}

.bg-gray-50 {
    background-color: #f9fafb;
}

.rounded-lg {
    border-radius: 0.5rem;
}

/* 图片容器样式 */
.comment-image {
    max-width: 300px;
    /* 限制最大宽度 */
    max-height: 200px;
    /* 限制最大高度 */
    width: auto;
    /* 保持图片比例 */
    height: auto;
    /* 保持图片比例 */
    border-radius: 8px;
    /* 圆角 */
    object-fit: cover;
    /* 保持比例并填充容器 */
    transition: transform 0.3s ease;
    /* 添加过渡效果 */
}

.comment-input {
    height: 10%;
    background-color: #fff;
    border-top: 1px solid #eee;
    position: sticky;
    bottom: 0;
    background: white;
    z-index: 10;
}

.input-container {
    position: relative;
}

.input-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}

.comment-textarea {
    :deep(.el-textarea__inner) {
        border-radius: 12px;
        padding: 12px 16px;
        resize: none;
        box-shadow: none;
    }
}</style>